/*-----------------------------------------------------------------------------
	The contents of this file are subject to the Mozilla Public License
	Version 1.1 (the "License"); you may not use this file except in
	compliance with the License.You may obtain a copy of the License at
	http://www.mozilla.org/MPL/MPL-1.1.html
	
	Software distributed under the License is distributed on an "AS IS"
	basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	License for the specific language governing rights and limitations
	under the License.
	
	The Original Code is Fever Framework code.
	
	The Initial Developer of the Original Code is Romain Ecarnot.
	Portions created by Initial Developer are Copyright (C) 2006
	the Initial Developer. All Rights Reserved.
	
	Contributor(s):
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
-----------------------------------------------------------------------------*/

import fever.data.crypt.ICrypter;

/**
 * <strong>RC4</strong> string encryption.
 * 
 * <p>Orignal ActionScript 2.0 implementation by Mika Palmu in his 
 * AsCrypt library, available in http://www.meychi.com/
 * 
 * @author Mika Palmu
 * @author Romain Ecarnot
 */
class fever.data.crypt.RC4 implements ICrypter
{
	//-------------------------------------------------------------------------
	// Private properties
	//-------------------------------------------------------------------------
	
	private static var mykey : Array = new Array(255);
	private static var sbox : Array = new Array(255);
	private static var _instance : ICrypter;
	
		
	//-------------------------------------------------------------------------
	// Public API
	//-------------------------------------------------------------------------
	
	/**
	 * Returns the RC4 crypter.
	 */
	public static function getProcess() : ICrypter
	{
		if( !_instance ) _instance = new RC4();
		return _instance;	
	}
	
	/**
	 * Encrypts a string with the specified key.
	 */
	public function encrypt( value , key : String ) : String
	{
		var mtxt : Array = _strToChars( value.toString() );
		var mkey : Array = _strToChars( key );
		var ouput : Array = _calculate( mtxt, mkey );
		return _charsToHex(ouput);
	}
	
	/**
	 * Decrypts a string with the specified key.
	 */
	public function decrypt( value , key : String) : String
	{
		var mtxt : Array = _hexToChars( value.toString() );
		var mkey : Array = _strToChars( key );
		var ouput : Array = _calculate( mtxt, mkey );
		return _charsToStr(ouput);
	}
	
	
	//-------------------------------------------------------------------------
	// Private implementation
	//-------------------------------------------------------------------------
	
	/**
	 * Constructor.
	 */
	private function RC4()
	{
		
	}
	
	private function _initialize(pwd:Array)
	{
		var b:Number = 0;
		var tempSwap:Number;
		var intLength:Number = pwd.length;
		for (var a:Number = 0; a <= 255; a++)
		{
			mykey[a] = pwd[(a%intLength)];
			sbox[a] = a;
		}
		for (var a:Number=0; a<=255; a++)
		{
			b = (b+sbox[a]+mykey[a]) % 256;
			tempSwap = sbox[a];
			sbox[a] = sbox[b];
			sbox[b] = tempSwap;
		}
	}
	
	private function _calculate(plaintxt:Array, psw:Array) : Array
	{
		_initialize(psw);
		var i:Number = 0; var j:Number = 0;
		var cipher:Array = new Array();
		var k:Number, temp:Number, cipherby:Number;
		for (var a:Number = 0; a<plaintxt.length; a++) {
			i = (i+1) % 256;
			j = (j+sbox[i])%256;
			temp = sbox[i];
			sbox[i] = sbox[j];
			sbox[j] = temp;
			var idx:Number = (sbox[i]+sbox[j]) % 256;
			k = sbox[idx];
			cipherby = plaintxt[a]^k;
			cipher.push(cipherby);
		}
		return cipher;
	}
	
	private function _charsToHex(chars:Array):String
	{
		var output : String = new String("");
		var hexes:Array = new Array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");
		for (var i:Number = 0; i<chars.length; i++) {
			output += hexes[chars[i] >> 4] + hexes[chars[i] & 0xf];
		}
		return output;
	}
	
	private function _hexToChars(hex:String) : Array
	{
		var codes:Array = new Array();
		for (var i:Number = (hex.substr(0, 2) == "0x") ? 2 : 0; i<hex.length; i+=2)
		{
			codes.push(parseInt(hex.substr(i, 2), 16));
		}
		return codes;
	}
	
	private function _charsToStr(chars:Array) : String
	{
		var output:String = new String("");
		for (var i:Number = 0; i<chars.length; i++)
		{
			output += String.fromCharCode(chars[i]);
		}
		return output;
	}
	
	private function _strToChars(str:String) : Array
	{
		var codes:Array = new Array();
		for (var i:Number = 0; i<str.length; i++) {
			codes.push(str.charCodeAt(i));
		}
		return codes;
	}
}